package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.mapper.DtsPermissionMapper;
import com.qf.pojo.DtsPermission;
import com.qf.service.DtsPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 邢式瑞
 * @version 1.0
 * @project E-commercebackGroundManagementSystem
 * @date 2022/9/22 23:08
 */
@Service
public class DtsPermissionServiceImpl implements DtsPermissionService {
    @Autowired
    private DtsPermissionMapper dtsPermissionMapper;
    @Override
    public void updatePermissionByRoleId(Integer roleId, List<String> permissions) {
        List<DtsPermission> dtsPermissions=dtsPermissionMapper.selectList(new QueryWrapper<DtsPermission>().eq("role_id",roleId).eq("deleted",false));
        List<String> permissionList = dtsPermissions.stream().map(dtsPermission -> {
            return dtsPermission.getPermission();
        }).collect(Collectors.toList());
        ArrayList<DtsPermission> dtsPermissions1 = new ArrayList<>();
        if (permissions != null) {
            for (String permission : permissions) {
                if(!permissionList.contains(permission)){
                    DtsPermission dtsPermission=new DtsPermission();
                    dtsPermission.setAddTime(new Date());
                    dtsPermission.setUpdateTime(new Date());
                    dtsPermission.setPermission(permission);
                    dtsPermission.setRoleId(roleId);
                    dtsPermission.setDeleted(false);
                    dtsPermissions1.add(dtsPermission);

                }
            }
        }
        ArrayList deleteArrayList = new ArrayList();
        for (DtsPermission dtsPermission : dtsPermissions) {
            if(!permissions.contains(dtsPermission.getPermission())){
                deleteArrayList.add(dtsPermission);
            }
        }
        if(deleteArrayList.size()!=0){
            dtsPermissionMapper.updateListDelete(deleteArrayList);
        }

        if(dtsPermissions1!=null) {
            dtsPermissionMapper.insertPremission(dtsPermissions1);
        }
    }

    @Override
    public Set<String> findDtsPremissionByRoleId(Integer roleId) {
        List<DtsPermission> dtsPermissions = dtsPermissionMapper.selectList(new QueryWrapper<DtsPermission>().select("permission").eq("role_id", roleId).eq("deleted",false));
        Set<String> collect = dtsPermissions.stream().map(DtsPermission::getPermission).collect(Collectors.toSet());
        return collect;
    }
}
